package com.wtwd.campus.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.wtwd.campus.adapter.*;
import com.wtwd.campus.adapter.HxyAdapter;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.entity.VerifyResult;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.Sha256Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AccessFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);

    @Autowired
    private RedisService redisService;

    private static final String WX_URL = "/wx";
    private static final String WEB_URL = "/web";
    private static final String CUSTOMER_URL = "/web/customer";
    private static final String H5_URL = "/web/h5";
    private static final String HXY_URL = "/web/hxy";
    private static final String VCOM_URL = "/web/vcom";
    private static final String XCX_URL = "/web/jdzc";
    private static final String H5_web="/web/webH5-manage";


    /**
     * 过滤器类型
     *
     * @return
     */
    @Override
    public String filterType() {
        /*pre：可以在请求被路由之前调用
          route：在路由请求时候被调用
          post：在route和error过滤器之后被调用
          error：处理请求时发生错误时被调用*/
        return "pre";
    }

    /**
     * 优先级
     *
     * @return
     */
    @Override
    public int filterOrder() {
        // 优先级为0，数字越大，优先级越低
        return 0;
    }

    /**
     * 是否该执行过滤器
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        return !(uri.contains("/web/user/login") || uri.contains("/wx/verifyWxUser") || uri.contains("/wx/subscribeByScan")
                || uri.contains("/wx/subscribeXBByScan")
                || uri.contains("/customer/getAccessToken")
                || uri.contains("/customer/refreshAccessToken")
                || uri.contains(".xlsx") || uri.contains(".xls")
                || uri.contains("/sys/excelImportTemplate/")
                || uri.contains("/device/importThirdPartDevice")
                || uri.contains("/device/importVcomLtDevice")
                || uri.contains("/device/importVcomDevice")
                || uri.contains("/wx/subscribeRyByScan") || uri.contains("/xmly/getStudentListByOpenId")
                || uri.contains("/web/location/getDistance/") || uri.contains("/vcom/identity/getAccessToken") || uri.contains("/vcom/h5/")
                || uri.contains("/jdzc/user/login")
                ||uri.contains("/web/webH5-manager/login")
                ||uri.contains("/web/fjry")
        );
    }

    /**
     * 执行内容
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        // 获取当前请求
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        // 设置响应信息
        HttpServletResponse response = requestContext.getResponse();
        // 设置编码格式
        response.setContentType("application/json;charset=UTF-8");
        // 针对请求进行分类
        String requestUrl = request.getRequestURI();
        if (requestUrl.contains("/location/info")) {
            String key = request.getParameter("key");
            if (key == null || !"fa88c1bfe3bb41c5854fcce95b25fe1f".equals(key)) {
                requestContext.setSendZuulResponse(false); // 过滤该请求，不对其进行路由
                String result = JSONObject.toJSONString(new RespEntity(RespCode.TOKEN_UNAUTHORIZED));
                requestContext.setResponseBody(result);
                return null;
            }
        } else {
            VerifyAdapter verifyAdapter = null;
            if (requestUrl.contains(WX_URL)) {
                logger.info("微信公众号调用" + requestUrl);
                verifyAdapter = new WxVerifyAdapter(request);
            } else if (requestUrl.contains(XCX_URL)) {
                verifyAdapter= new JdzcAdapter(request);
            } else if (requestUrl.contains(CUSTOMER_URL)) {
                verifyAdapter = new CustomerVerifyAdapter(request);
            } else if (requestUrl.contains(H5_URL)) {
                verifyAdapter = new H5Adapter(request);
            } else if (requestUrl.contains(HXY_URL)) {
                verifyAdapter = new HxyAdapter(request);
            } else if (requestUrl.contains(VCOM_URL)) {
                verifyAdapter = new VcomAdapter(request);
            } else if (requestUrl.contains(H5_web)){
                verifyAdapter=new H5ManageAdapter(request);
            }else {
                verifyAdapter = new WebVerifyAdapter(request);
            }
            VerifyResult verifyResult = verifyAdapter.verifyEncrypt(request, redisService);
            if (verifyResult != null) {
                if (verifyResult.isResult()) {
                    if (verifyResult.getHttpServletRequest() != null) {
                        request = verifyResult.getHttpServletRequest();
                    }
                    return null;
                } else {
                    requestContext.setSendZuulResponse(false);
                    String result = JSONObject.toJSONString(new RespEntity(verifyResult.getRespCode()));
                    requestContext.setResponseBody(result);
                    return null;
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String token = "9b691b8c92d44975ab14d0b8cf9dc7ce";
        String param = "1{\"param\":1}";
        String result = Sha256Utils.SHA256(token + param);
        System.out.println(result);
    }
}
